import { useMount, useUpdateEffect } from 'ahooks';
import { createGlobalStore } from 'hox';
import { useState } from 'react';

export const getDarkMode = () => localStorage.getItem('darkMode');

const [useDarkMode] = createGlobalStore(() => {
  const [currentDarkMode, setCurrentDarkMode] = useState<'light' | 'dark'>('light');
  const switchDarkMode = () => setCurrentDarkMode(currentDarkMode === 'light' ? 'dark' : 'light');

  useMount(() => {
    const darkMode = getDarkMode();
    if (darkMode && darkMode === 'dark') {
      setCurrentDarkMode('dark');
    }
    document.body.className = currentDarkMode === 'dark' ? 'dark' : 'light';
  });

  useUpdateEffect(() => {
    localStorage.setItem('darkMode', currentDarkMode);
    document.body.className = currentDarkMode === 'dark' ? 'dark' : 'light';
  }, [currentDarkMode]);

  return { currentDarkMode, switchDarkMode };
});

export default useDarkMode;
